﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MovieDbLib;
using MovieDbLib.Data;
using MovieDbLib.Data.Banner;
using System.IO;
using System.Drawing.Imaging;
using MovieDbLib.Cache;
using MovieDbLib.Data.Persons;

namespace MovieDbBrowser
{
  /// <summary>
  /// Interaction logic for Window1.xaml
  /// </summary>
  public partial class Window1 : Window
  {
    MovieDbHandler m_handler;
    MovieDbMovie selectedMovie;
    public Window1()
    {
      InitializeComponent();

      if (File.Exists("api_key.txt"))
      {
        XmlCacheProvider cacheProvider = new XmlCacheProvider(@"d:\test");
        cacheProvider.InitCache();

        m_handler = new MovieDbHandler(File.ReadAllText("api_key.txt"), cacheProvider);
      }
      else
      {
        MessageBox.Show("Make sure you have your api key in a file called \"api_key.txt\" in the same folder as the application",
                        "No Api key found");
      }

    }

    private void cmdGetMovie_Click(object sender, RoutedEventArgs e)
    {
      selectedMovie = m_handler.GetMovie(Int32.Parse(txtMovieId.Text), new MovieDbLanguage(0, "en", "English"));
      if (selectedMovie != null)
      {
        UpdateForm(selectedMovie);
      }
      else
      {
        MessageBox.Show("No movie available for id " + txtMovieId.Text);
      }
    }

    private void cmdGetImdbMovie_Click(object sender, RoutedEventArgs e)
    {
      selectedMovie = m_handler.GetMovie(txtImdbId.Text, null);
      if (selectedMovie != null)
      {
        UpdateForm(selectedMovie);
      }
      else
      {
        MessageBox.Show("No movie available for imdb id " + txtImdb.Text);
      }

    }

    private void cmdSearchMovie_Click(object sender, RoutedEventArgs e)
    {
      MovieSearch search = new MovieSearch(m_handler, txtMovieSearchString.Text);
      if (search.ShowDialog() == true)
      {
        selectedMovie = m_handler.GetMovie(search.SelectedMovie, new MovieDbLanguage(0, "en", "English"));
        UpdateForm(selectedMovie);
      }
    }

    private void UpdateForm(MovieDbMovie _movie)
    {
      txtId.Text = selectedMovie.Id.ToString();
      txtMovieName.Text = selectedMovie.MovieName;
      txtOverview.Text = selectedMovie.Overview;
      txtPopularity.Text = selectedMovie.Popularity.ToString();
      txtAlternativeNames.Text = selectedMovie.AlternativeName;
      txtImdb.Text = selectedMovie.AlternativeName;
      txtHomepage.Text = selectedMovie.Homepage;
      txtReleased.Text = selectedMovie.Released.ToString();
      txtBudget.Text = selectedMovie.Budget.ToString();
      txtRevenue.Text = selectedMovie.Revenue.ToString();
      lbPersons.ItemsSource = _movie.Cast;
      lbCategories.ItemsSource = _movie.Categories;

      if (selectedMovie.Posters.Count > 0)
      {
        List<MovieDbBanner> posterList = new List<MovieDbBanner>();
        selectedMovie.Posters.ForEach(delegate(MovieDbPoster p) { posterList.Add((MovieDbBanner)p); });
        imgPosterBanner.BannerImages = posterList;
      }

      if (selectedMovie.Backdrops.Count > 0)
      {
        List<MovieDbBanner> backdropList = new List<MovieDbBanner>();
        selectedMovie.Backdrops.ForEach(delegate(MovieDbBackdrop b) { backdropList.Add((MovieDbBanner)b); });
        imgBackdropBanner.BannerImages = backdropList;
      }
    }



    private void cmdOriginal_Click(object sender, RoutedEventArgs e)
    {
      MovieDbPoster poster = selectedMovie.Posters[0];
      if (!poster.Original.IsLoaded)
      {
        poster.Original.LoadBanner();
      }
      // ImageSource ...

      BitmapImage bi = new BitmapImage();
      bi.BeginInit();
      MemoryStream ms = new MemoryStream();

      // Save to a memory stream...
      poster.Original.BannerImage.Save(ms, ImageFormat.Jpeg);

      // Rewind the stream...
      ms.Seek(0, SeekOrigin.Begin);

      // Tell the WPF image to use this stream...
      bi.StreamSource = ms;

      bi.EndInit();
      imgPoster.Source = bi;
    }

    private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

    }

    private void lbPersons_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      MovieDbCast cast = ((MovieDbCast)lbPersons.SelectedItem);

      MovieDbPerson person = m_handler.GetPerson(cast.Id, null);
      UpdatePerson(person, cast);
    }

    private void UpdatePerson(MovieDbPerson _person, MovieDbCast _cast)
    {
      if (_person != null)
      {
        txtPersonId.Text = _person.Id.ToString();
        txtPersonName.Text = _person.Name + (_cast.Character == null ? "" : " as " + _cast.Character);
        txtPersonAka.Text = _person.AlsoKnownAsString;
        txtPersonUrl.Text = _person.Url;
        pbPersonPopularity.Value = (int)_person.Popularity;
        txtPersonKnownMovies.Text = _person.KnownMovies.ToString();
        txtPersonBorn.Text = _person.Birthday.ToShortDateString() + ", " + _person.Birthplace;

        if (_person.Images != null && _person.Images.Count > 0)
        {
          imgPersonBanner.BannerImages = _person.Images;
        }
        else
        {
          imgPersonBanner.BannerImages = null;
        }
      }
    }



  }
}
